package point

import (
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/app"
	"sweetsunnyflower/pkg/database"
	"sweetsunnyflower/pkg/paginator"

	"github.com/gin-gonic/gin"
)

func Get(idstr string) (point Point) {
	database.DB.Where("id", idstr).First(&point)
	return
}

func GetBy(field, value string) (point Point) {
	database.DB.Where("? = ?", field, value).First(&point)
	return
}

func All() (points []Point) {
	database.DB.Find(&points)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(Point{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func Paginate(c *gin.Context, perPage int) (points []Point, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(Point{}),
		&points,
		app.V1URL(database.TableName(&Point{})),
		perPage,
	)
	return
}

// 获取积分记录
func GetByLatestId(query requests.PointQueryRequest) (points []Point) {

	model := database.DB

	if query.UserID > 0 {
		model = model.Where("user_id = ?", query.UserID)
	}

	if query.Action > 0 {
		model = model.Where("action = ?", query.Action)
	}

	if query.Type > 0 {
		model = model.Where("type = ?", query.Type)
	}

	if query.LatestId > 0 {
		model = model.Where("id < ?", query.LatestId)
	}

	model.Order("id desc").Limit(query.Limit).Find(&points)

	return
}

// 获取积分记录
func Count(query requests.PointQueryRequest) (count int64) {

	model := database.DB.Model(&Point{})

	if query.UserID > 0 {
		model = model.Where("user_id = ?", query.UserID)
	}

	if query.Action > 0 {
		model = model.Where("action = ?", query.Action)
	}

	if query.Type > 0 {
		model = model.Where("type = ?", query.Type)
	}

	model.Count(&count)

	return
}

func Sum(query requests.PointQueryRequest) (sum int64) {

	model := database.DB.Model(&Point{})

	if query.UserID > 0 {
		model = model.Where("user_id = ?", query.UserID)
	}

	if query.Action > 0 {
		model = model.Where("action = ?", query.Action)
	}

	if query.Type > 0 {
		model = model.Where("type = ?", query.Type)
	}

	model.Select("sum(value) as sum").Scan(&sum)

	return
}
